<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-row>
        <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon></el-alert>
      </el-row>
      <!-- 选择商品分类区域 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange(cateId)"
            clearable
            style="width: 300px"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 动态参数、静态属性Tabs标签 -->
      <el-row>
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <!-- 动态参数区域 -->
          <el-tab-pane label="动态参数" name="many">
            <el-button @click="showAddParamsDialog" type="primary" :disabled="selectedKeys.length ===3? false: true">添加动态参数</el-button>
            <!-- 动态参数表格 -->
            <el-table :data="manyData" border stripe style="width: 100%">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="index"
                    closable
                    @close="removeTag(index,scope.row)"
                    type="success"
                  >{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                    style="width: 200px"
                  ></el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="编号"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="showEditParamsDialog(scope.row)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                  <el-button @click="removeParams(scope.row)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 静态属性区域 -->
          <el-tab-pane label="静态属性" name="only">
            <el-button @click="showAddParamsDialog" type="primary" :disabled="selectedKeys.length ===3? false: true">添加静态属性</el-button>
            <!-- 静态属性表格 -->
            <el-table :data="onlyData" border stripe style="width: 100%">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="index"
                    closable
                    @close="removeTag(index,scope.row)"
                    type="success"
                  >{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                    style="width: 200px"
                  ></el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="编号"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="showEditParamsDialog(scope.row)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                  <el-button @click="removeParams(scope.row)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-card>

    <!-- 添加动态参数/静态属性对话框 -->
    <el-dialog
      :title="'添加' + paramsTitle"
      :visible.sync="addParamsDialogVisible"
      @close="addParamsDialogClosed"
      width="50%">
      <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="addParamsFormRef" label-width="100px">
        <el-form-item :label="paramsTitle" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

     <!-- 编辑动态参数/静态属性对话框 -->
    <el-dialog
      :title="'编辑' + paramsTitle"
      :visible.sync="editParamsDialogVisible"
      @close="editParamsDialogClosed"
      width="50%">
      <el-form :model="editParamsForm" :rules="editParamsFormRules" ref="editParamsFormRef" label-width="100px">
        <el-form-item :label="paramsTitle" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 选中的分类id
      selectedKeys: [],
      // 配置级联选择器选项
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        // 展开子选项方式
        expandTrigger: 'hover'
      },
      // tabs当前激活标签
      activeName: 'many',
      // 动态参数数据
      manyData: [],
      // 静态属性数据
      onlyData: [],
      // 添加参数表单数据
      addParamsForm: {
        attr_name: ''
      },
      // 添加参数表单验证规则
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制是否显示添加参数对话框
      addParamsDialogVisible: false,
      // 控制是否显示编辑参数对话框
      editParamsDialogVisible: false,
      // 编辑参数表单数据
      editParamsForm: {
        attr_id: '',
        attr_name: ''
      },
      // 编辑参数表单验证规则
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类信息失败')
      }
      this.cateList = res.data
    },
    // 监听级联选择器值变化
    async handleChange() {
      // 若选择的不是第3级分类
      if (this.selectedKeys.length !== 3) {
        // 让级联选择器清空
        this.selectedKeys = []
        // 若不是第3级分类，不渲染动态参数/静态属性表格
        this.manyData = []
        this.onlyData = []
        return
      }
      // 发送请求，获取相关参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类参数失败')
      }
      console.log(res.data)
      res.data.forEach((item) => {
        // 将服务器端返回的attr_vals字符串分割成数组形式，方便渲染tag标签
        item.attr_vals = item.attr_vals.length > 0 ? item.attr_vals.split(' ') : []
        // 为每个数据行添加inputVisible控制自己展开行中输入框是否显示
        item.inputVisible = false
        // 添加一个inputValue保存文本框值
        item.inputValue = ''
      })
      // 若选中的是动态参数标签
      if (this.activeName === 'many') {
        this.manyData = res.data
      } else {
        // 若选中的是静态属性标签
        this.onlyData = res.data
      }
    },
    // 切换tabs标签显示对应的表格
    handleTabClick() {
      this.handleChange()
    },
    // 点击NewTag标签,显示输入框
    showInput(row) {
      row.inputVisible = true
      // $nextTick:在页面上元素被重新渲染之后，调用回调函数的代码
      this.$nextTick(_ => {
        // 让文本框自动获去焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 监听输入框值更改
    handleInputConfirm(row) {
      // 判断用户输入是否有效
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 向当前列数据的attr_vals推送输入框的值
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    // 删除动态参数tag标签
    removeTag(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    },
    // 封装函数,保存动态参数选项
    async saveAttrVals(row) {
      // 发送请求
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败')
      }
      this.$message.success('修改参数项成功')
    },
    // 点击添加按钮，显示对应的对话框
    showAddParamsDialog() {
      this.addParamsDialogVisible = true
    },
    // 添加参数
    addParams() {
      // 表单预校验
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        // 校验通过，发送请求
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加' + this.paramsTitle + '失败')
        }
        // 添加成功，响应信息
        this.$message.success('添加' + this.paramsTitle + '成功')
        this.handleChange()
        this.addParamsDialogVisible = false
      })
    },
    // 关闭添加参数对话框
    addParamsDialogClosed() {
      this.$refs.addParamsFormRef.resetFields()
    },
    // 点击编辑按钮，显示对应的对话框
    showEditParamsDialog(row) {
      this.editParamsForm.attr_name = row.attr_name
      this.editParamsForm.attr_id = row.attr_id
      this.editParamsDialogVisible = true
    },
    // 编辑参数，提交表单发送请求
    editParams() {
      // 表单预校验
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        // 校验通过，发送请求
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('编辑' + this.paramsTitle + '失败')
        }
        // 添加成功，响应信息
        this.$message.success('编辑' + this.paramsTitle + '成功')
        this.handleChange()
        this.editParamsDialogVisible = false
      })
    },
    // 关闭编辑参数对话框
    editParamsDialogClosed() {
      this.$refs.editParamsFormRef.resetFields()
    },
    // 删除参数
    async removeParams(row) {
      const confirmResult = await this.$confirm('此操作将永久删除该项' + this.paramsTitle + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 若点击确定，返回字符串confirm,反之，返回字符串cancel
      if (confirmResult !== 'confirm') {
        this.$message.info('已取消删除操作')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除' + this.paramsTitle + '失败')
      }
      this.$message.success('删除' + this.paramsTitle + '成功')
      this.handleChange()
    }
  },
  computed: {
    // 计算被选中分类的id值
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[this.selectedKeys.length - 1]
      } else {
        return null
      }
    },
    // 计算属性，点击tab标签，添加参数显示相对应的对话框
    paramsTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin-bottom: 15px;
}

.el-tag {
  margin: 10px;
}
</style>
